package page

import (
	"fmt"
	"net/url"
	"strconv"

	"gitee.com/haodreams/golib/easyroute/group"
	"gitee.com/haodreams/libs/easy"
	"gitee.com/haodreams/libs/tailsnap"
	"github.com/gin-gonic/gin"
	"golang.org/x/text/encoding/simplifiedchinese"
)

type TailLogController struct {
	group.Group
}

// 有IFrame的页面
func (m *TailLogController) Tail(c *gin.Context) {
	vals, _ := url.ParseQuery(c.Request.URL.RawQuery)
	prefix := ""
	day := ""
	code := ""
	size := 50

	val := vals["prefix"]
	if len(val) > 0 {
		prefix = val[0]
	}
	val = vals["day"]
	if len(val) > 0 {
		day = val[0]
		if day == "now" {
			day = easy.FormatNow(easy.YMD)
		}
	}
	val = vals["code"]
	if len(val) > 0 {
		code = val[0]
	}

	val = vals["size"]
	if len(val) > 0 {
		num, err := strconv.Atoi(val[0])
		if err == nil {
			if num < 10 {
				size = 10
			} else if num > 1000 {
				size = 1000
			} else {
				size = num
			}
		}
	}

	c.Writer.Header().Add("Content-Type", "text/html; charset=utf-8")
	path := fmt.Sprintf("%s%s.log", prefix, day)
	lines, err := tailsnap.TailFile(path, size)
	if err != nil {
		c.Writer.WriteString(err.Error())
		fmt.Fprintln(c.Writer, "</br>", `
		<script>
			function onClose() {
				var iframe = parent.document.getElementById('customdlg');
				iframe.style.height = "0px";
				iframe.style.width = "0px";
				iframe.src=""
			 }
		 </script>
	 <input type="button" value="关闭窗口" onclick="onClose()">`)
		return
	}
	fmt.Fprintln(c.Writer, "<pre>")
	for _, line := range lines {
		if line != nil {
			if code == "GBK" {
				str, _ := simplifiedchinese.GBK.NewEncoder().String(*line)
				c.Writer.WriteString(str)
			} else {
				c.Writer.WriteString(*line)
			}
			c.Writer.WriteString("\r\n")
		}
	}
	fmt.Fprintln(c.Writer, "</pre>")
	fmt.Fprintln(c.Writer, `
				<script>
					function onClose() {
            			var iframe = parent.document.getElementById('customdlg');
            			iframe.style.height = "0px";
            			iframe.style.width = "0px";
						iframe.src=""
			 		}
					function onReload() {
                        parent.document.getElementById('customdlg').contentWindow.location.reload(true);
                	}
			 	</script>
			 <input type="button" value="关闭窗口" onclick="onClose()">
			 <input type="button" value="刷新" onclick="onReload()">`)
}

// 无IFrame的页面
func (m *TailLogController) TailLog(c *gin.Context) {
	vals, _ := url.ParseQuery(c.Request.URL.RawQuery)
	prefix := ""
	day := ""
	code := ""
	size := 50

	val := vals["prefix"]
	if len(val) > 0 {
		prefix = val[0]
	}
	val = vals["day"]
	if len(val) > 0 {
		day = val[0]
		if day == "now" {
			day = easy.FormatNow(easy.YMD)
		}
	}
	val = vals["code"]
	if len(val) > 0 {
		code = val[0]
	}

	val = vals["size"]
	if len(val) > 0 {
		num, err := strconv.Atoi(val[0])
		if err == nil {
			if num < 10 {
				size = 10
			} else if num > 1000 {
				size = 1000
			} else {
				size = num
			}
		}
	}

	path := fmt.Sprintf("%s%s.log", prefix, day)
	lines, err := tailsnap.TailFile(path, size)
	if err != nil {
		c.Writer.WriteString(err.Error())
		return
	}
	c.Writer.Header().Add("Content-Type", "text/html")
	c.Writer.WriteString(`<!DOCTYPE html>
		<html> <head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
		<title>查看日志</title>
		</head><body>`)

	fmt.Fprintln(c.Writer, "<pre>")
	for _, line := range lines {
		if line != nil {
			if code == "GBK" {
				str, _ := simplifiedchinese.GBK.NewEncoder().String(*line)
				c.Writer.WriteString(str)
			} else {
				c.Writer.WriteString(*line)
			}
			c.Writer.WriteString("\r\n")
		}
	}
	c.Writer.WriteString("</pre>")
	c.Writer.WriteString(`<script>
		function onReload() {location.reload(true);}
	 </script>
 <input type="button" value="刷新" onclick="onReload()">`)
	c.Writer.WriteString("</body></html>")
}


func TailFile(c *gin.Context) {
	vals, _ := url.ParseQuery(c.Request.URL.RawQuery)
	prefix := ""
	day := ""
	size := 50

	val := vals["prefix"]
	if len(val) > 0 {
		prefix = val[0]
	}
	val = vals["day"]
	if len(val) > 0 {
		day = val[0]
		if day == "now" {
			day = easy.FormatNow(easy.YMD)
		}
	}

	val = vals["size"]
	if len(val) > 0 {
		num, err := strconv.Atoi(val[0])
		if err == nil {
			size = min(max(num, 10), 1000)
		}
	}

	c.Writer.Header().Add("Content-Type", "text/plain; charset=utf-8")
	path := fmt.Sprintf("%s%s", prefix, day)
	lines, err := tailsnap.TailFile(path, size)
	if err != nil {
		c.Writer.WriteString(err.Error())
		return
	}
	for _, line := range lines {
		if line != nil {
			c.Writer.WriteString(*line)
			c.Writer.WriteString("\n")
		}
	}
}
